import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class SegmentPage extends StatelessWidget {
  const SegmentPage({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('多级地区选择'),
        ),
        body: Center(
          child: MultiLevelRegionSelector(),
        ),
      ),
    );
  }
}

class MultiLevelRegionSelector extends StatefulWidget {
  @override
  _MultiLevelRegionSelectorState createState() =>
      _MultiLevelRegionSelectorState();
}

class _MultiLevelRegionSelectorState extends State<MultiLevelRegionSelector> {
  int _selectedProvinceIndex = 0;
  int _selectedCityIndex = 0;

  final List<String> provinces = ['广东', '浙江', '江苏'];
  final Map<String, List<String>> provinceCities = {
    '广东': ['广州', '深圳', '珠海'],
    '浙江': ['杭州', '宁波', '温州'],
    '江苏': ['南京', '苏州', '无锡'],
  };

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 省级分段控制器
        CupertinoSegmentedControl<int>(
          children: Map<int, Widget>.fromIterable(
            provinces.asMap().entries,
            key: (entry) => entry.key,
            value: (entry) => Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Text(entry.value),
            ),
          ),
          onValueChanged: (int? newValue) {
            if (newValue != null) {
              setState(() {
                _selectedProvinceIndex = newValue;
                _selectedCityIndex = 0; // 当省份改变时，重置城市选择
              });
            }
          },
          groupValue: _selectedProvinceIndex,
        ),
        SizedBox(height: 20),
        // 市级分段控制器
        CupertinoSegmentedControl<int>(
          children: Map<int, Widget>.fromIterable(
            provinceCities[provinces[_selectedProvinceIndex]]!.asMap().entries,
            key: (entry) => entry.key,
            value: (entry) => Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Text(entry.value),
            ),
          ),
          onValueChanged: (int? newValue) {
            if (newValue != null) {
              setState(() {
                _selectedCityIndex = newValue;
              });
            }
          },
          groupValue: _selectedCityIndex,
        ),
        SizedBox(height: 20),
        Text(
          '你选择的地区是: ${provinces[_selectedProvinceIndex]} - ${provinceCities[provinces[_selectedProvinceIndex]]![_selectedCityIndex]}',
          style: TextStyle(fontSize: 18),
        ),
      ],
    );
  }
}